#!/bin/bash
# 安装Node.js

# 引入公共配置
source ./common.sh

# 确保应用目录存在
app_home

function install_node() {
    local version=`echo ${Version} |awk -F. '{print $1}' `
    local link="node-v${Version}-linux-x64.tar.gz"
    
    if [ ! -e "${APPS_HOME}/$link" ];then
        echo "正在下载Node.js ${Version}..."
        wget -P ${APPS_HOME} "${NODE_NAME}"v"${Version}"/node-v"${Version}"-linux-x64.tar.gz
        if [ $? -ne 0 ]; then
            error_exit "Node.js下载失败"
        fi
    fi
    
    mkdir -p ${Basedir}/node && tar -xf ${APPS_HOME}/$link -C ${Basedir}/node --strip-components 1
    rm -rf /usr/local/bin/npm && rm -rf /usr/local/bin/node
    ln -s ${Basedir}/node/bin/npm /usr/local/bin/npm
    ln -s ${Basedir}/node/bin/node /usr/local/bin/node
    
    if [ $? -eq 0 ];then
        success_msg "node ${Version} 安装成功"
        node -v
        npm -v
    else
        error_exit "node安装失败"
    fi
}

echo "开始安装Node.js..."

read -p "输入需要的node版本(默认16.15.0): " Version
if [ -z "${Version}" ];then
    Version="16.15.0"
    echo "使用默认版本: $Version"
fi

install_node
